// pages/my/my-team/index.js
const WXAPI = require('../../../miniprogram_npm/apifm-wxapi/index.js')
const CONFIG = require('../../../config.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 团队信息
    teamInfo: {
      totalMembers: 0,
      activeMembers: 0,
      newMembers: 0
    },
    
    // 成员列表
    members: [],
    filteredMembers: [],
    
    // 搜索和筛选
    searchKeyword: '',
    currentTab: 'all',
    
    // 页面状态
    loading: true,
    showActionModal: false,
    selectedMember: null,
    canManage: false,
    
    // 分页
    page: 1,
    pageSize: 20,
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkUserPermission()
    this.loadTeamData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时刷新数据
    this.loadTeamData()
  },

  /**
   * 检查用户权限
   */
  checkUserPermission() {
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    // 检查是否有管理权限
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      canManage: userInfo && (userInfo.isLeader || userInfo.isAdmin)
    })
  },

  /**
   * 加载团队数据
   */
  async loadTeamData() {
    try {
      this.setData({ loading: true })
      
      // 并行请求团队信息和成员列表
      const [teamInfoRes, membersRes] = await Promise.all([
        this.getTeamInfo(),
        this.getTeamMembers()
      ])
      
      if (teamInfoRes && membersRes) {
        this.processTeamData(teamInfoRes, membersRes)
      }
    } catch (error) {
      console.error('加载团队数据失败:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 获取团队信息
   */
  async getTeamInfo() {
    const token = wx.getStorageSync('token')
    try {
      // 这里应该调用实际的API接口
      // const res = await WXAPI.request('/team/info', true, 'GET', { token })
      
      // 模拟数据
      return {
        code: 0,
        data: {
          totalMembers: 156,
          activeMembers: 89,
          newMembers: 12
        }
      }
    } catch (error) {
      console.error('获取团队信息失败:', error)
      return null
    }
  },

  /**
   * 获取团队成员列表
   */
  async getTeamMembers() {
    const token = wx.getStorageSync('token')
    const { page, pageSize } = this.data
    
    try {
      // 这里应该调用实际的API接口
      // const res = await WXAPI.request('/team/members', true, 'POST', {
      //   token,
      //   page,
      //   pageSize
      // })
      
      // 模拟数据
      const mockMembers = this.generateMockMembers()
      return {
        code: 0,
        data: {
          list: mockMembers,
          hasMore: page < 3
        }
      }
    } catch (error) {
      console.error('获取成员列表失败:', error)
      return null
    }
  },

  /**
   * 生成模拟数据
   */
  generateMockMembers() {
    const members = []
    const roles = ['leader', 'admin', 'member']
    const levels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    for (let i = 1; i <= 20; i++) {
      const joinDate = new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000)
      const lastActiveDate = new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000)
      
      members.push({
        id: i,
        nickname: `团队成员${i}`,
        avatar: `https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKxrUx${i}/132`,
        isOnline: Math.random() > 0.3,
        isLeader: i === 1,
        isAdmin: i <= 3 && i > 1,
        isVip: Math.random() > 0.7,
        level: levels[Math.floor(Math.random() * levels.length)],
        joinTime: this.formatDate(joinDate),
        lastActiveTime: this.formatDate(lastActiveDate),
        contribution: Math.floor(Math.random() * 10000),
        inviteCount: Math.floor(Math.random() * 50),
        orderCount: Math.floor(Math.random() * 200),
        isNewMember: (Date.now() - joinDate.getTime()) < 30 * 24 * 60 * 60 * 1000
      })
    }
    
    return members
  },

  /**
   * 处理团队数据
   */
  processTeamData(teamInfoRes, membersRes) {
    const teamInfo = teamInfoRes.data
    const membersList = membersRes.data.list
    const hasMore = membersRes.data.hasMore
    
    // 更新团队信息
    this.setData({
      teamInfo,
      members: this.data.page === 1 ? membersList : [...this.data.members, ...membersList],
      hasMore
    })
    
    // 应用当前筛选条件
    this.filterMembers()
  },

  /**
   * 筛选成员
   */
  filterMembers() {
    const { members, searchKeyword, currentTab } = this.data
    let filtered = [...members]
    
    // 按关键词搜索
    if (searchKeyword) {
      filtered = filtered.filter(member => 
        member.nickname.toLowerCase().includes(searchKeyword.toLowerCase())
      )
    }
    
    // 按标签筛选
    switch (currentTab) {
      case 'active':
        filtered = filtered.filter(member => member.isOnline)
        break
      case 'new':
        filtered = filtered.filter(member => member.isNewMember)
        break
      default:
        // 全部成员，不需要额外筛选
        break
    }
    
    this.setData({ filteredMembers: filtered })
  },

  /**
   * 搜索输入处理
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    
    // 防抖处理
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      this.filterMembers()
    }, 300)
  },

  /**
   * 切换标签
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: tab
    })
    this.filterMembers()
  },

  /**
   * 查看成员详情
   */
  viewMemberDetail(e) {
    const member = e.currentTarget.dataset.member
    wx.navigateTo({
      url: `/pages/member/detail/index?memberId=${member.id}`
    })
  },

  /**
   * 与成员聊天
   */
  chatWithMember(e) {
    const member = e.currentTarget.dataset.member || this.data.selectedMember
    
    // 这里可以集成客服系统或跳转到聊天页面
    wx.showToast({
      title: `正在打开与${member.nickname}的聊天`,
      icon: 'none'
    })
    
    this.hideActionModal()
  },

  /**
   * 显示成员操作菜单
   */
  showMemberActions(e) {
    const member = e.currentTarget.dataset.member
    this.setData({
      selectedMember: member,
      showActionModal: true
    })
  },

  /**
   * 隐藏操作菜单
   */
  hideActionModal() {
    this.setData({
      showActionModal: false,
      selectedMember: null
    })
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  /**
   * 查看成员资料
   */
  viewMemberProfile() {
    const member = this.data.selectedMember
    wx.navigateTo({
      url: `/pages/member/profile/index?memberId=${member.id}`
    })
    this.hideActionModal()
  },

  /**
   * 设置成员权限
   */
  setMemberRole() {
    const member = this.data.selectedMember
    wx.showActionSheet({
      itemList: ['设为管理员', '设为普通成员', '设为VIP成员'],
      success: (res) => {
        const roles = ['admin', 'member', 'vip']
        const role = roles[res.tapIndex]
        this.updateMemberRole(member.id, role)
      }
    })
    this.hideActionModal()
  },

  /**
   * 移除成员
   */
  removeMember() {
    const member = this.data.selectedMember
    wx.showModal({
      title: '确认移除',
      content: `确定要移除成员"${member.nickname}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.doRemoveMember(member.id)
        }
      }
    })
    this.hideActionModal()
  },

  /**
   * 更新成员权限
   */
  async updateMemberRole(memberId, role) {
    try {
      const token = wx.getStorageSync('token')
      // const res = await WXAPI.request('/team/member/role', true, 'POST', {
      //   token,
      //   memberId,
      //   role
      // })
      
      wx.showToast({
        title: '权限设置成功',
        icon: 'success'
      })
      
      // 刷新数据
      this.loadTeamData()
    } catch (error) {
      wx.showToast({
        title: '设置失败，请重试',
        icon: 'none'
      })
    }
  },

  /**
   * 执行移除成员
   */
  async doRemoveMember(memberId) {
    try {
      const token = wx.getStorageSync('token')
      // const res = await WXAPI.request('/team/member/remove', true, 'POST', {
      //   token,
      //   memberId
      // })
      
      wx.showToast({
        title: '移除成功',
        icon: 'success'
      })
      
      // 刷新数据
      this.loadTeamData()
    } catch (error) {
      wx.showToast({
        title: '移除失败，请重试',
        icon: 'none'
      })
    }
  },

  /**
   * 邀请新成员
   */
  inviteMembers() {
    wx.navigateTo({
      url: '/pages/team/invite/index'
    })
  },

  /**
   * 团队管理
   */
  manageTeam() {
    if (!this.data.canManage) {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: '/pages/team/manage/index'
    })
  },

  /**
   * 格式化日期
   */
  formatDate(date) {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    
    if (days === 0) {
      return '今天'
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else if (days < 30) {
      return `${Math.floor(days / 7)}周前`
    } else if (days < 365) {
      return `${Math.floor(days / 30)}个月前`
    } else {
      return `${Math.floor(days / 365)}年前`
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 1,
      members: [],
      hasMore: true
    })
    this.loadTeamData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.hasMore || this.data.loading) {
      return
    }
    
    this.setData({
      page: this.data.page + 1
    })
    this.loadTeamData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '加入我们的团队',
      path: '/pages/team/join/index',
      imageUrl: '/images/team-share.png'
    }
  }
})